package cn.yyh.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author 杨永航
 * @version 1.0
 * @Title: LoginInterceptor
 * @Package: cn.yyh.basic.interceptor
 * @date 2021/7/2
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!ObjectUtils.isEmpty(token)) {
            Object value = redisTemplate.opsForValue().get(token);
            if (value != null) {
                redisTemplate.opsForValue().set(token,value,30, TimeUnit.MINUTES);
                return true;
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"code\":50014,\"message\":\"请重新登陆\",\"success\":false}");
        return false;
    }
}
